package com.bdk.middle.management.config;

import com.bdk.middle.management.api.domain.AdminDO;
import com.bdk.middle.management.filter.CustomAuthenticationFilter;
import com.bdk.middle.management.filter.JWTAuthorizationFilter;
import com.bdk.middle.management.jwt.JwtAuthenticationEntryPoint;
import com.bdk.middle.management.jwt.JwtTokenUtil;
import com.bdk.middle.management.service.PermissionService;
import com.bdk.middle.management.service.RoleService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.bdk.middle.common.status.ErrorCode;
import com.bdk.middle.common.result.web.ObjectResponse;
import com.bdk.middle.management.service.impl.AdminUserDetailsService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.filters.CorsFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
@Slf4j
@EnableGlobalMethodSecurity(securedEnabled=true,prePostEnabled=true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private Logger                  logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private AdminUserDetailsService adminService;

    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RoleService roleService;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors()
                .and()
                .csrf()
                .and().authorizeRequests()
                .antMatchers("/jsonLogin.html").permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilterAt(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class)
                .addFilter(new JWTAuthorizationFilter(authenticationManager(),permissionService,roleService))
                .formLogin()
                .loginPage("/index.html")
                .loginProcessingUrl("/jsonLogin.html")
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .logout().logoutUrl("/logout.html")
                .and()
                .exceptionHandling().accessDeniedHandler(new AccessDeniedHandler() {
            @Override
            public void handle(HttpServletRequest req, HttpServletResponse resp, AccessDeniedException e) throws IOException, ServletException {
                ObjectResponse response = new ObjectResponse();
                resp.setContentType("application/json;charset=utf-8");
                response.setStatus(ErrorCode.UNAUTHORIZED_EXCEPTION.getCode());
                response.setMsg(ErrorCode.UNAUTHORIZED_EXCEPTION.getMsg());
                PrintWriter out = resp.getWriter();
                out.write(new ObjectMapper().writeValueAsString(response));
                out.flush();
                out.close();
            }
        }).authenticationEntryPoint(new JwtAuthenticationEntryPoint());

    }


    @Override
    public void configure(WebSecurity web) throws Exception {

        web.ignoring(). antMatchers("/swagger-ui.html")
                .antMatchers("/**")
                .antMatchers("/webjars/**")
                .antMatchers("/v2/**")
                .antMatchers("/swagger-resources/**");
    }

    @Bean
    CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
        CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
        filter.setAuthenticationManager(super.authenticationManagerBean());
        filter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
                ObjectResponse response = new ObjectResponse();

                AdminDO user= (AdminDO) authentication.getPrincipal();
                // 从User中获取权限信息
                Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
                String roleJson = "";
                if(authorities != null) {
                    Gson gson = new Gson();
                    roleJson = gson.toJson(authorities);
                }
                // 创建Token
                String token = JwtTokenUtil.createToken(user.getUsername(), roleJson);

                // 设置编码 防止乱码问题
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("application/json; charset=utf-8");
                // 在请求头里返回创建成功的token
                // 设置请求头为带有"Bearer "前缀的token字符串
                //resp.setHeader("token", JwtTokenUtil.TOKEN_PREFIX + token);
                resp.setContentType("application/json;charset=utf-8");
                response.setData(authentication.getPrincipal());
                PrintWriter out = resp.getWriter();
                response.setData(JwtTokenUtil.TOKEN_PREFIX + token);
                out.write(new ObjectMapper().writeValueAsString(response));
                out.flush();
                out.close();
            }
        });
        filter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException e) throws IOException, ServletException {
                ObjectResponse response = new ObjectResponse();
                response.setMsg("登录失败,用户名或者密码错误");
                response.setStatus(ErrorCode.NOT_LOGIN.getCode());
                resp.setContentType("application/json;charset=utf-8");
                PrintWriter out = resp.getWriter();
                out.write(new ObjectMapper().writeValueAsString(response));
                out.flush();
                out.close();
            }
        });
        filter.setFilterProcessesUrl("/jsonLogin.html");
        return filter;
    }

   @Autowired
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        //校验用户
        auth.userDetailsService(adminService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordUtil();
    }


}
